package com.shushan.home;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.common.ui.LimitScrollerView;
import com.android.common.ui.OnRecyclerviewItemClickListener;
import com.android.common.ui.banner.BannerConfig;
import com.android.common.ui.banner.listener.OnBannerListener;
import com.android.common.ui.indicator.ViewPagerIndicator;
import com.android.fingerprintidentify.FingerprintIdentify;
import com.android.fingerprintidentify.base.BaseFingerprint;
import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.andview.refreshview.XRefreshView;
import com.shushan.base.BaseHomeFragment;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.db.ChildBookDao;
import com.shushan.exercise.SmartExerciseActivity;
import com.shushan.exercise.SyncExerciseActivity;
import com.shushan.home.adapter.ExerciseHomeAdapter;
import com.shushan.home.adapter.HomeLimitScrollAdapter;
import com.shushan.home.adapter.WhiteAppsHAdapter;
import com.shushan.home.bean.BannerDataBean;
import com.shushan.home.bean.HomeIndexBean;
import com.shushan.lockscreen.bean.AppInfo;
import com.shushan.mixedexam.OralCalculateExerciseActivity;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.InviteForFreeUseActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.pages.SpecialTopicVideoActivity;
import com.shushan.pages.VkeListActivity;
import com.shushan.pages.newtype.EnglishWordsExerciseActivity;
import com.shushan.pages.newtype.HearingExerciseActivity;
import com.shushan.pages.newtype.SpeakingExerciseActivity;
import com.shushan.pages.newtype.StrangeWordsExerciseActivity;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.service.ForegroundRTAService;
import com.shushan.setting.ParentSettingActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.HomeBanner;
import com.shushan.ui.RefreshHeader;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.ControlUtil;
import com.shushan.util.GlideImageLoader;
import com.shushan.util.ImageUtils;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToolUtils;
import com.shushan.util.UmengEventUtil;
import com.shushan.web.AdvertWebActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: HomeFragment
 * @Desciption: 首页
 * @author: yichaohua
 * @date: 2018-12-08
 */
public class HomeFragment extends BaseHomeFragment implements XRefreshView.XRefreshViewListener, OnExerciseClickListener, LimitScrollerView.OnItemClickListener, View.OnClickListener, VerificationCodeView.OnCodeFinishListener, OnRecyclerviewItemClickListener {

    private static final String TAG = "HomeFragment";

    private XRefreshView xRefreshView;
    private LimitScrollerView limitScrollerView;
    private HomeLimitScrollAdapter homeLimitScrollAdapter;
    private RecyclerView whiteRecyclerView;
    private RecyclerView exerciseRecyclerView;
    private HomeBanner mBanner;
    private TextView whiteHintText;
    private ViewPagerIndicator viewPagerIndicator;
    private TextView tvRightGrade;
    private LinearLayout gradeLayout;
    private Dialog changeToParentDialog;
    private VerificationCodeView veriCodeView;
    private Dialog noBookDialog;
    private Dialog noVipDialog;

    private WhiteAppsHAdapter whiteAppsAdapter;
    private ExerciseHomeAdapter exerciseHomeAdapter;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private List<BannerDataBean> bannerDataBeanList;
    private FingerprintIdentify mFingerprintIdentify;

    private int znlx = 0;//0、没有智能练习 1、有智能练习
    private int priority_completion = 0;//0、优先智能练习开关->关,1、打开


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_fragment, null);
        ScreenManager sm = new ScreenManager();
        if (!sm.setDeepStatusBar(true, getActivity())) {
            view.findViewById(R.id.titlebar_divider).setVisibility(View.GONE);
        }

        initView(view);

        //初始化广告栏
        initBanner();

        boolean isEyeOpen = SharedPreferencesUtils.getBooleanDate(Constants.PROJECT_EYE_SWITCH_SHAREPREFERS_KEY);
        if (isEyeOpen) {
            int eyeInterval = SharedPreferencesUtils.getIntDate(Constants.PROJECT_EYE_INTERVAL_SHAREPREFERS_KEY);
            ControlUtil.setEyeProjectAlarm(getActivity(), eyeInterval);
        }

        xRefreshView.startRefresh();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        tvRightGrade.setText(ToolUtils.getLevelTermText(shuShanApplication.getCurrentChildBean()));
    }

    @Override
    public void onStart() {
        super.onStart();

        limitScrollerView.startScroll();
        mBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();

        limitScrollerView.cancel();
        mBanner.stopAutoPlay();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (noBookDialog != null) {
            noBookDialog.dismiss();
        }

        if (noVipDialog != null) {
            noVipDialog.dismiss();
        }

        if (changeToParentDialog != null) {
            changeToParentDialog.dismiss();
        }

        if (mFingerprintIdentify != null) {
            mFingerprintIdentify.cancelIdentify();
        }
    }

    private void initView(View view) {
        mBanner = view.findViewById(R.id.banner);
        whiteRecyclerView = view.findViewById(R.id.home_white_rv);
        exerciseRecyclerView = view.findViewById(R.id.home_exercise_rv);
        exerciseRecyclerView.setNestedScrollingEnabled(false);
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(getActivity());
        layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        whiteRecyclerView.setLayoutManager(layoutManager1);
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(getActivity());
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        exerciseRecyclerView.setLayoutManager(layoutManager2);
        whiteAppsAdapter = new WhiteAppsHAdapter(getActivity());
        whiteAppsAdapter.setRecyclerviewItemClickListener(this);
        whiteRecyclerView.setAdapter(whiteAppsAdapter);
        exerciseHomeAdapter = new ExerciseHomeAdapter(getActivity());
        exerciseHomeAdapter.setOnExerciseClickListener(this);
        exerciseRecyclerView.setAdapter(exerciseHomeAdapter);
        DividerItemDecoration dec = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        dec.setDrawable(new ColorDrawable(Color.parseColor("#DEDEDE")));
        exerciseRecyclerView.addItemDecoration(dec);
        whiteHintText = view.findViewById(R.id.child_main_white_hint_tv);
        limitScrollerView = view.findViewById(R.id.home_limitview);
        limitScrollerView.setOnItemClickListener(this);
        homeLimitScrollAdapter = new HomeLimitScrollAdapter(getActivity());
        limitScrollerView.setDataAdapter(homeLimitScrollAdapter);
        xRefreshView = view.findViewById(R.id.child_main_refv);
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setXRefreshViewListener(this);
        xRefreshView.setCustomHeaderView(new RefreshHeader(getActivity()));
        viewPagerIndicator = view.findViewById(R.id.home_indicator);
        tvRightGrade = view.findViewById(R.id.actionbar_right_grade_tv);
        tvRightGrade.setText(ToolUtils.getLevelTermText(shuShanApplication.getCurrentChildBean()));
        gradeLayout = view.findViewById(R.id.actionbar_right_grade_layout);
        gradeLayout.setOnClickListener(this);
    }

    @Override
    public void onFragmentChecked() {

        getData();
    }

    @Override
    public void onFragmentHided() {

    }

    @Override
    public void onRefresh() {
        new GetAppListTask().execute();
        getData();
    }

    @Override
    public void onRefresh(boolean isPullDown) {

    }

    @Override
    public void onLoadMore(boolean isSilence) {

    }

    @Override
    public void onRelease(float direction) {

    }

    @Override
    public void onHeaderMove(double headerMovePercent, int offsetY) {

    }

    private void getData() {
        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(getActivity(), UrlConst.BASE_URL).appendRegion(UrlConst.GET_HOME_INDEX);
        urlParse.putValue("child_id", childId);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<HomeIndexBean>() {
                    @Override
                    protected void onCommon() {
                        xRefreshView.stopRefresh();
                    }

                    @Override
                    protected void onSuccess(HomeIndexBean indexBean) {
                        if (indexBean != null) {
                            znlx = indexBean.znlx;
                            priority_completion = indexBean.priority_completion;

                            bannerDataBeanList = indexBean.getBannerDataBeanList();

                            homeLimitScrollAdapter.setBannerDataBeanList(indexBean.getNoticeDataBeanList());

                            limitScrollerView.startScroll();
                            exerciseHomeAdapter.setExerciseBeanList(indexBean.getExerciseBeanList());
                            exerciseHomeAdapter.notifyDataSetChanged();
                            setBanner();
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public void onExerciseClick(boolean isOk, int exerciseType) {
        Log.i(TAG, "exerciseType=" + exerciseType);

        if (!(isOk || (exerciseType == Constants.TYPE_SMART_EXERCISE))) {
            if (!isExerciseValide(exerciseType)) {
                return;
            }
        }

        switch (exerciseType) {
            case Constants.TYPE_SYNC_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication, "sync_exercise_click_id");
                startActivity(SyncExerciseActivity.class);
                break;
            case Constants.TYPE_SMART_EXERCISE:
                startActivity(SmartExerciseActivity.class);
                break;
            case Constants.TYPE_STRANGE_WORDS_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication, "words_exercise_click_id");
                startActivity(StrangeWordsExerciseActivity.class);
                break;
            case Constants.TYPE_ORAL_CALCULATE_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication, "oral_exercise_click_id");
                startActivity(OralCalculateExerciseActivity.class);
                break;
            case Constants.TYPE_SPEAKING_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication, "speaking_exercise_click_id");
                startActivity(SpeakingExerciseActivity.class);
                break;
            case Constants.TYPE_ENGLISH_WORDS_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication, "english_words_exercise_click_id");
                startActivity(EnglishWordsExerciseActivity.class);
                break;
            case Constants.TYPE_HEARING_EXERCISE:
                UmengEventUtil.onEvent(shuShanApplication, "hearing_exercise_click_id");
                startActivity(HearingExerciseActivity.class);
                break;
            case Constants.TYPE_CHINESE_SECT_EXERCISE:
            case Constants.TYPE_MACH_SECT_EXERCISE:
            case Constants.TYPE_ENGLISH_SECT_EXERCISE:
                Intent intent = new Intent(getActivity(), SyncExerciseActivity.class);
                intent.putExtra("awardType", exerciseType);
                startActivityAllow(intent);
                break;
            case Constants.TYPE_V_CHINESE_EXERCISE:
                Intent intent1 = new Intent(getActivity(), VkeListActivity.class);
                intent1.putExtra("subjectId", Constants.SUBJECT_CHINESE_ID);
                startActivityAllow(intent1);
                break;
            case Constants.TYPE_V_MACH_EXERCISE:
                Intent intent2 = new Intent(getActivity(), VkeListActivity.class);
                intent2.putExtra("subjectId", Constants.SUBJECT_MACH_ID);
                startActivityAllow(intent2);
                break;
            case Constants.TYPE_V_ENGLISH_EXERCISE:
                Intent intent3 = new Intent(getActivity(), VkeListActivity.class);
                intent3.putExtra("subjectId", Constants.SUBJECT_ENGLISH_ID);
                startActivityAllow(intent3);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(Object obj) {
        if (obj instanceof BannerDataBean) {
            //强制转换
            BannerDataBean bean = (BannerDataBean) obj;
            bannerJump(bean);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.actionbar_right_grade_layout:
                showToParentDialog();
                break;
            default:
                break;
        }
    }

    @Override
    public void onComplete(String content) {
        if (StringTools.pswValide(content)) {
            if (changeToParentDialog != null) {
                changeToParentDialog.dismiss();
            }

            startActivity(ParentSettingActivity.class);
        } else {
            showToast("家长密码错误");
            if (veriCodeView != null) {
                veriCodeView.clear();
            }
        }
    }

    @Override
    public void onItemClickListener(View v, int position) {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if (isChildControl && !SystemUtils.checkUsagePermission(getActivity())) {
            showNoUsageDialog();
            return;
        }

        List<AppInfo> appInfoList = whiteAppsAdapter.getAppInfoList();
        AppInfo appInfo = appInfoList.get(position);

        super.setAllowBack(true);
        SystemUtils.startApp(getActivity(), appInfo.getPackageName());

        if (isChildControl) {
            Intent intent = new Intent(getActivity(), ForegroundRTAService.class);
            intent.putExtra("paperId", -1);
            intent.putExtra("allowPackName", appInfo.getPackageName());
            intent.putExtra("allowAppLabel", appInfo.getLabel());
            intent.putExtra("isWhitePlay", true);

            getActivity().startService(intent);
        }
    }

    private class GetAppListTask extends AsyncTask<Void, Void, List<AppInfo>> {

        @Override
        protected List<AppInfo> doInBackground(Void... voids) {
            List<AppInfo> appInfoList = SystemUtils.getUsePackages(true, getActivity());

            return appInfoList;
        }

        @Override
        protected void onPostExecute(List<AppInfo> appInfoList) {
            if (ToolUtils.isListEmpty(appInfoList)) {
                whiteHintText.setVisibility(View.VISIBLE);
                whiteRecyclerView.setVisibility(View.GONE);
                return;
            } else {
                whiteHintText.setVisibility(View.GONE);
                whiteRecyclerView.setVisibility(View.VISIBLE);
            }

            whiteAppsAdapter.setAppInfoList(appInfoList);
            whiteAppsAdapter.notifyDataSetChanged();
        }
    }

    private void initBanner() {
        mBanner.setBannerStyle(BannerConfig.NOT_INDICATOR).setImageLoader(new GlideImageLoader(R.drawable.banner_empty));
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (ToolUtils.isListEmpty(bannerDataBeanList)) {
                    return;
                } else {
                    BannerDataBean dataBean = bannerDataBeanList.get(position);
                    bannerJump(dataBean);
                }
            }
        });
    }

    private void setBanner() {
        if (ToolUtils.isListEmpty(bannerDataBeanList)) {
            Log.d(TAG, "banner数据为空");
            return;
        }
        List<String> images = new ArrayList<String>();
        for (BannerDataBean bean : bannerDataBeanList) {
            String loadUrl;
            if (ImageUtils.isAbsoluteUrl(bean.pic)) {
                loadUrl = bean.pic;
            } else {
                loadUrl = BuildConfig.imgBaseUrl + bean.pic;
            }
            images.add(loadUrl);
        }
        mBanner.setImages(images).start();
        mBanner.setIndicator(viewPagerIndicator, images.size());
    }

    //根据type跳转不同界面
    private void bannerJump(BannerDataBean dataBean) {
        switch (dataBean.type) {
            case 0://跳转H5
                Intent intent2 = new Intent(getActivity(), AdvertWebActivity.class);
                intent2.putExtra("url", dataBean.url);
                startActivityAllow(intent2);
                break;
            case 1://跳转APP页面
                if (dataBean.url.equals("0")) {
                    startActivity(InviteForFreeUseActivity.class);
                } else if (!TextUtils.isEmpty(dataBean.android_name)) {
                    try {
                        Intent intent1 = new Intent();
                        intent1.setClassName(getContext(), dataBean.android_name);
                        startActivityAllow(intent1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 2://跳转视频页面
                Intent intent = new Intent(getActivity(), SpecialTopicVideoActivity.class);
                intent.putExtra("isOnlyPlay", true);
                intent.putExtra("video_title", dataBean.name);
                intent.putExtra("video_url", dataBean.url);
                startActivityAllow(intent);
                break;
            case 3://专项练习
                onExerciseClick(false, dataBean.practice_type);
                break;
            case 4:
                UmengEventUtil.onEvent(shuShanApplication, "home_101_download_click_id", dataBean.android_name);
                SystemUtils.openAppMarket(getActivity(), dataBean.android_name);
                break;
            default:
                break;
        }
    }

    private void showToParentDialog() {
        if (changeToParentDialog == null) {
            changeToParentDialog = new Dialog(getActivity(), R.style.Dialog_Translucent_Background);
            changeToParentDialog.setContentView(R.layout.change_to_parent_dialog);
            changeToParentDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

            veriCodeView = changeToParentDialog.findViewById(R.id.verification_code_view);
            veriCodeView.setOnCodeFinishListener(this);
            Button coloseButton = changeToParentDialog.findViewById(R.id.btn_cancel);
            coloseButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    changeToParentDialog.dismiss();
                    if (mFingerprintIdentify != null) {
                        mFingerprintIdentify.cancelIdentify();
                    }
                }
            });

            changeToParentDialog.setCancelable(false);
        }

        if (mFingerprintIdentify == null) {
            mFingerprintIdentify = new FingerprintIdentify(BabyApplication.getInstance(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
                @Override
                public void onCatchException(Throwable exception) {
                    Log.e(TAG, exception.getLocalizedMessage());
                }
            });
        }

        ImageView parentImg = changeToParentDialog.findViewById(R.id.parent_psw_img);
        ImageView fingerIconImg = changeToParentDialog.findViewById(R.id.parent_finger_icon_img);
        final TextView hintText = changeToParentDialog.findViewById(R.id.parent_dialog_hint_tv);
        hintText.setVisibility(View.GONE);
        if (mFingerprintIdentify.isFingerprintEnable()
                && mFingerprintIdentify.isHardwareEnable()
                && mFingerprintIdentify.isRegisteredFingerprint()) {

            parentImg.setVisibility(View.GONE);
            fingerIconImg.setVisibility(View.VISIBLE);

            ((TextView) changeToParentDialog.findViewById(R.id.parent_dialog_tv)).setText("请验证指纹或者家长密码去设置");

            mFingerprintIdentify.startIdentify(5, new BaseFingerprint.FingerprintIdentifyListener() {
                @Override
                public void onSucceed() {
                    startActivity(ParentSettingActivity.class);
                    changeToParentDialog.dismiss();
                }

                @Override
                public void onNotMatch(int availableTimes) {
                    hintText.setVisibility(View.VISIBLE);
                    hintText.setText("指纹不匹配，还剩余" + availableTimes + "次机会");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);

                }

                @Override
                public void onFailed(boolean isDeviceLocked) {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);
                }

                @Override
                public void onStartFailedByDeviceLocked() {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);
                }
            });
        } else {
            parentImg.setVisibility(View.VISIBLE);
            fingerIconImg.setVisibility(View.GONE);
            ((TextView) changeToParentDialog.findViewById(R.id.parent_dialog_tv)).setText("请输入家长密码去设置");
        }

        if (veriCodeView != null) {
            veriCodeView.clear();
        }

        if (!changeToParentDialog.isShowing()) {
            changeToParentDialog.show();
        }
    }

    private boolean isExerciseValide(int exerciseType) {
        int subjectId = 0;
        if (exerciseType == Constants.TYPE_STRANGE_WORDS_EXERCISE
                || exerciseType == Constants.TYPE_CHINESE_SECT_EXERCISE
                || exerciseType == Constants.TYPE_V_CHINESE_EXERCISE) {
            subjectId = Constants.SUBJECT_CHINESE_ID;
        } else if (exerciseType == Constants.TYPE_ORAL_CALCULATE_EXERCISE
                || exerciseType == Constants.TYPE_MACH_SECT_EXERCISE
                || exerciseType == Constants.TYPE_V_MACH_EXERCISE) {
            subjectId = Constants.SUBJECT_MACH_ID;
        } else if (exerciseType == Constants.TYPE_SPEAKING_EXERCISE
                || exerciseType == Constants.TYPE_ENGLISH_WORDS_EXERCISE
                || exerciseType == Constants.TYPE_HEARING_EXERCISE
                || exerciseType == Constants.TYPE_ENGLISH_SECT_EXERCISE
                || exerciseType == Constants.TYPE_V_ENGLISH_EXERCISE) {
            subjectId = Constants.SUBJECT_ENGLISH_ID;
        }

        ChildBookDao childBookDao = new ChildBookDao(getActivity());
        if (!childBookDao.containSubject(subjectId)) {
            showNoBookDialog(subjectId);
            return false;
        }

        int vipType = exerciseType;
        if (exerciseType == Constants.TYPE_V_CHINESE_EXERCISE
                || exerciseType == Constants.TYPE_V_MACH_EXERCISE
                || exerciseType == Constants.TYPE_V_ENGLISH_EXERCISE) {
            vipType = Constants.TYPE_SYNC_EXERCISE;
        }

        if (!shuShanApplication.isSectVip(vipType)) {
            showNoVipDialog(exerciseType, subjectId);
            return false;
        }

        if (znlx + priority_completion == 2) {
            showMustSmartDialog();
            return false;
        }

//        int gameTime = SharedPreferencesUtils.getIntDate(Constants.EXIST_GAME_TIME_SHAREPREFERS_KEY
//                + shuShanApplication.getCurrentChildId());
//        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
//        if(isChildControl && gameTime > 0){
//            showExistTimeDialog(exerciseType);
//            return false;
//        }

        return true;
    }

    private void showNoBookDialog(int subjectId) {
        noBookDialog = new Dialog(getActivity(), R.style.Dialog_Translucent_Background);
        noBookDialog.setCanceledOnTouchOutside(true);
        noBookDialog.setContentView(R.layout.no_book_dialog);

        TextView textView = noBookDialog.findViewById(R.id.no_book_tv);
        if (subjectId == Constants.SUBJECT_CHINESE_ID) {
            textView.setText("请添加语文课本！");
        } else if (subjectId == Constants.SUBJECT_MACH_ID) {
            textView.setText("请添加数学课本！");
        } else if (subjectId == Constants.SUBJECT_ENGLISH_ID) {
            textView.setText("请添加英语课本！");
        }

        Button addButton = noBookDialog.findViewById(R.id.no_book_postitve_btn);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noBookDialog.dismiss();
                showToParentDialog();
            }
        });

        Button cancelButton = noBookDialog.findViewById(R.id.no_book_cancel_btn);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noBookDialog.dismiss();

            }
        });


        if (!noBookDialog.isShowing()) {
            noBookDialog.show();
        }
    }

    private void showNoVipDialog(final int exerciseType, final int subjectId) {
        noVipDialog = new Dialog(getActivity(), R.style.Dialog_Translucent_Background);
        noVipDialog.setCanceledOnTouchOutside(true);
        noVipDialog.setContentView(R.layout.no_sect_vip_dialog);

        Button tryoutButton = noVipDialog.findViewById(R.id.no_vip_tryout_btn);
        if (subjectId < 0) {
            tryoutButton.setVisibility(View.GONE);
        }
        tryoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noVipDialog.dismiss();
                onExerciseClick(true, exerciseType);
            }
        });

        Button openSectBtn = noVipDialog.findViewById(R.id.no_vip_open_sect_btn);
        openSectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noVipDialog.dismiss();

                Intent intent = new Intent(getActivity(), OpenSectVipActivity.class);
                intent.putExtra("exerciseType", exerciseType);
                startActivityAllow(intent);
            }
        });

        Button openAllBtn = noVipDialog.findViewById(R.id.no_vip_open_all_btn);
        openAllBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noVipDialog.dismiss();
                startActivity(OpenVipSpendActivity.class);
            }
        });


        if (!noVipDialog.isShowing()) {
            noVipDialog.show();
        }
    }

    private void showExistTimeDialog(final int exerciseType) {
        new CustomDialog.Builder(getActivity())
                .setTitle("温馨提示")
                .setMessage("发现您还有手机娱乐时间，是否去游戏？")
                .setNegativeButton("去学习", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        onExerciseClick(true, exerciseType);
                    }
                })
                .setPositiveButton("去娱乐", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        ControlUtil.gotoGamesFloat(getActivity());
                    }
                })
                .create().show();
    }

    private void showMustSmartDialog() {
        new CustomDialog.Builder(getActivity())
                .setTitle("温馨提示")
                .setMessage("发现您开启了优先智能练习开关，需要先完成智能练习!")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("去智能练习", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(SmartExerciseActivity.class);
                    }
                })
                .create().show();
    }

    private void showNoUsageDialog() {
        new CustomDialog.Builder(getActivity())
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启“有权查看应用使用情况”，将导致无法监控小孩玩手机情况，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenUsageActivity.class);
                    }
                })
                .create().show();
    }

}